package com.ellen.mac.chatdemo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.ellen.mac.chatdemo.activity.ImHomeActivty;
import com.ellen.mac.chatdemo.activity.StorageAct;
import com.ellen.mac.chatdemo.cache.ACache;
import com.ellen.mac.chatdemo.comment.BaseApp;
import com.ellen.mac.chatdemo.utils.ChatKit;
import com.ellen.mac.chatdemo.utils.LogUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.avos.avoscloud.Messages.CommandType.data;

@SuppressLint("NewApi")
public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    AVIMClient client;
    private ACache mCache;
    private EditText uName,password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uName = findViewById(R.id.username);
        password = findViewById(R.id.passwod);
        mayRequestContacts();
        mCache = ACache.get(this);
        uName.setText("OOK");
        password.setText("OOK");
    }

    public void logup(View view){
        if(uName.getText().toString().isEmpty()||uName.getText().toString().isEmpty()) {
            Toast.makeText(this,"some params lose",Toast.LENGTH_SHORT).show();
            return;
        }
        AVUser user = new AVUser();// 新建 AVUser 对象实例
        user.setUsername(uName.getText().toString());// 设置用户名
        user.setPassword(password.getText().toString());// 设置密码
        user.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    // 注册成功，把用户对象赋值给当前用户 AVUser.getCurrentUser()
                    Log.d("tag", "logupSuccess!");
                    mCache.put(BaseApp.USERNAME,uName.getText().toString());
                } else {
                    // 失败的原因可能有多种，常见的是用户名已经存在。
                    Log.d("tag", "fail"+e);
                    Toast.makeText(MainActivity.this,"fail"+e,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    public void login(View view){
        //todo User password

        if(uName.getText().toString().isEmpty()||uName.getText().toString().isEmpty()) {
            Toast.makeText(this,"some params lose",Toast.LENGTH_SHORT).show();
            return;
        }


        AVUser.logInInBackground(uName.getText().toString(), password.getText().toString(), new LogInCallback<AVUser>() {
            @Override
            public void done(final AVUser user, AVException e) {
                if (null != e) {
                    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    return;
                }
                // 与服务器连接
                mCache.put(BaseApp.USERNAME,uName.getText().toString());
                client = AVIMClient.getInstance(user);
                mCache.put(BaseApp.CLIENTID,client.getClientId());
                client.open(new AVIMClientCallback() {
                    @Override
                    public void done(final AVIMClient avimClient, AVIMException e) {
                        if (null != e) {
                            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(MainActivity.this,"login success",Toast.LENGTH_SHORT).show();
                        ChatKit.getInstance().open(user.getObjectId(),uName.getText().toString(), new AVIMClientCallback() {
                            @Override
                            public void done(AVIMClient avimClient, AVIMException e) {
                                if (null == e) {
                                    Toast.makeText(MainActivity.this, "login success", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(MainActivity.this,ImHomeActivty.class);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    }
                });
            }
        });

    }

    public void logout(View view){
        if(client == null){
            Toast.makeText(MainActivity.this,"please login !",Toast.LENGTH_LONG).show();
            return;
        }
        AVUser.getCurrentUser().logOut();
        client.close(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient client, AVIMException e) {
                if(e!=null){
                    return ;
                }else{
                    Log.d("Aven & test", "退出");
                }
            }
        });
    }

    public void toStorage(View v){
        if(mCache.getAsString(BaseApp.USERNAME)==null){
            Toast.makeText(MainActivity.this,"please login !",Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent = new Intent(MainActivity.this,StorageAct.class);
        startActivity(intent);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED||
                checkSelfPermission(RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED||
                checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_EXTERNAL_STORAGE)||
                shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)||
                shouldShowRequestPermissionRationale(RECORD_AUDIO)
                ) {
            requestPermissions(new String[]{READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,RECORD_AUDIO}, REQUEST_EXTERNAL_STORAGE);
        } else {
            requestPermissions(new String[]{READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,RECORD_AUDIO}, REQUEST_EXTERNAL_STORAGE);
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            if (grantResults.length == 1 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mayRequestContacts();
            }
        }
    }

}
